local system = CEGUI.System:getSingleton()
local wmgr = CEGUI.WindowManager:getSingleton()
local cursor = CEGUI.MouseCursor:getSingleton()

local dialogLayout = wmgr:loadWindowLayout("fileDialog.layout")

system:getGUISheet():addChildWindow(dialogLayout)

selectedFilename = ""

fileDialog = FileDialog:new()
fileDialog:setListWindowName("FileDialog/FileList")
fileDialog:setSelectionColour(0.25,0.3,0.6)
fileDialog:setDirectoryColour(0,0.1,1.0)
fileDialog:setFileFilter(".*\\.dfmap$")
wmgr:getWindow("FileDialog/FilterLabel"):setText("Filter: *.dfmap")
fileDialog:openPath('.')
wmgr:getWindow("FileDialog/FullPathLabel"):setText(fileDialog:getCurrentPath())

cursor:show()

function listbox_select(e)
    local listbox = CEGUI.toListbox(CEGUI.toWindowEventArgs(e).window)
    local selection = listbox:getFirstSelectedItem()
    if selection ~= nil then
        wmgr:getWindow("FileDialog/FilenameBox"):setText(selection:getText())
    end
end

function listbox_open(e)
    local listbox = CEGUI.toListbox(wmgr:getWindow("FileDialog/FileList"))
    local filenamebox = wmgr:getWindow("FileDialog/FilenameBox")
    local result = fileDialog:openPath(filenamebox:getText())
    if result==2 or result == 0 then
        listbox:clearAllSelections()
        filenamebox:setText("")
        wmgr:getWindow("FileDialog/FullPathLabel"):setText(fileDialog:getCurrentPath())
    elseif result==1 then
        selectedFilename = fileDialog:getFullPathName(filenamebox:getText())
        fileDialog:delete()
        system:getGUISheet():removeChildWindow("FileDialog")
    end
end
